package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeOrderBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/1/8 08:26
 */
public class Dws_08_DwsTradeOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_08_DwsTradeOrderWindow().init(
            4008,
            2,
            "Dws_08_DwsTradeOrderWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts") * 1000)
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(obj -> obj.getString("user_id"))
            .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {
    
                private ValueState<String> lastOrderDateState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastOrderDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastOrderDate", String.class));
                }
    
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<TradeOrderBean> out) throws Exception {
                    long ts = obj.getLong("ts") * 1000;
                    String today = AtguiguUtil.tsToDate(ts);
    
                    // 下单独立用户数
                    Long orderUniqueUserCount = 0L;
    
                    // 下单新用户数
                    Long orderNewUserCount = 0L;
    
                    String lastOrderDate = lastOrderDateState.value();
    
                    if (!today.equals(lastOrderDate)) {
                        // 今天第一次
                        orderUniqueUserCount = 1L;
                        lastOrderDateState.update(today);
                        
                        if (lastOrderDate == null) { // 是首次
                            orderNewUserCount = 1L;
                        }
                    }
    
                    if (orderUniqueUserCount == 1) {
                        out.collect(new TradeOrderBean(
                            "", "",
                            orderUniqueUserCount, orderNewUserCount,
                            ts
                        ));
                    }
    
                }
            })
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeOrderBean>() {
                    @Override
                    public TradeOrderBean reduce(TradeOrderBean value1,
                                                 TradeOrderBean value2) throws Exception {
                        value1.setOrderUniqueUserCount(value1.getOrderUniqueUserCount()+value2.getOrderUniqueUserCount());
                        value1.setOrderNewUserCount(value1.getOrderNewUserCount()+value2.getOrderNewUserCount());
                        return value1;
                    }
                },
                new AllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<TradeOrderBean> values,
                                      Collector<TradeOrderBean> out) throws Exception {
                        TradeOrderBean bean = values.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(window.getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(window.getEnd()));
        
                        bean.setTs(System.currentTimeMillis());
        
                        out.collect(bean);
                    }
                }
            )
            .addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_order_window", TradeOrderBean.class));
    }
}
/*
当日下单独立用户数和新增下单用户数


来源 dwd 层下单明细
detail_id  user_id    金额1  金额2   活动
1             10       100  200    null
null(消费是: 直接忽略)
1             10       100   200     有值

    

 */